package com.tengju.bff.interfaces.covercharge.controller.notify;

import com.google.common.base.Throwables;
import com.tengju.bff.interfaces.covercharge.service.NotifyService;
import com.tengju.bff.interfaces.covercharge.util.alarmUtil.MsgSendUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author liang_shi
 * @date 2020/7/24 9:49
 * @description 通知接受
 */
@Slf4j
@Controller
@Api(value = "notify", tags = "服务通知")
@RequestMapping(value = "/notify")
public class NotifyController {

    @Autowired
    private NotifyBizFactory notifyBizFactory;

    /**
     * 异步通知接受
     *
     * @param channel    渠道
     * @param bizType    业务类型
     * @param bizOrderNo 业务订单号-唯一
     * @param request    请求
     * @param response   响应
     */
    @RequestMapping("/{channel}/{bizType}/{bizOrderNo}")
    public void notify(
            @PathVariable("channel") String channel,
            @PathVariable("bizType") String bizType,
            @PathVariable("bizOrderNo") String bizOrderNo,
            @RequestBody Object reqObject,
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            //获取实现类
            NotifyService notifyService = notifyBizFactory.getBizFactoryImpl(channel, bizType);
            //验签
            HashMap resultBizMap = notifyService.signVerify(reqObject, request);
            boolean isSuccess = false;
            if (!Objects.isNull(resultBizMap)) {
                isSuccess = true;
            }
            //返回结果
            notifyService.writerReturn(isSuccess, response);
            //业务处理
            notifyService.executeBiz(bizOrderNo, resultBizMap);
        } catch (Exception e) {
            log.error("异步通知接受,处理异常:{}", Throwables.getStackTraceAsString(e));
            MsgSendUtil.sendLarkMsg("异步通知接受,处理异常,channel:{},bizType:{},单号:{}，异常：{}", channel, bizType, bizOrderNo, Throwables.getStackTraceAsString(e));
        }
    }


}
